package com.abc.robot01.activity

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.abc.robot01.R

import androidx.compose.material3.MaterialTheme
import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.sp
import androidx.lifecycle.lifecycleScope
import com.abc.robot01.room.DatabaseContext
import com.abc.robot01.room.bean.ChatAnswerBean
import com.abc.robot01.room.bean.ChatQuestionBean
import com.abc.robot01.room.bean.CmdBean
import com.abc.robot01.vivemodel.AddQAViewModel
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch
import java.time.LocalDate
import java.time.format.DateTimeFormatter



class AddQAActivity : BaseVoiceActivity() {

    private val viewModel: AddQAViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val cmd_id =  this.intent.getLongExtra("cmd_id",-1);
        lifecycleScope.launch(IO) {
            if (cmd_id != -1L) {
                viewModel.questionList.clear()
                viewModel.questionList.addAll(
                    DatabaseContext.getChatQuestionDao()
                        .queryCustomQuestionByCmdId(cmd_id.toString()).map {
                        QuestionBean(id = it.id, question = it.question)
                    })

                DatabaseContext.getChatAnswerDao().qryAllAnswer().forEach {
                    Log.e(TAG, "$it" + it.ttsText + "" + it.cmd_Id);
                }
                val answer =
                    DatabaseContext.getChatAnswerDao().qryCustomAnswerByCmdId(cmd_id.toString());
                viewModel.answer.id = answer.id
                viewModel.answer.answer = answer.ttsText
                Log.e(TAG, "answer: " + viewModel.answer)
            }
        }

        viewModel.cmdId = cmd_id

        setContent {
            val scrollState = rememberScrollState()
            MaterialTheme {
                Box {
                    Image(painter = painterResource(id = R.drawable.z1), contentDescription = "")
                    Row(modifier = Modifier.padding(30.px)) {
                        BackButton{
                        }

                        Spacer(modifier = Modifier.width(82.px))
                        Column(modifier = Modifier
                            .fillMaxHeight()
                            .width(1400.px)) {
                            BasicText(
                                text = "新增语音配置",
                                style = TextStyle(
                                    fontSize = 30.mysp,
                                    color = Color.Black,
                                    fontWeight = FontWeight.Bold
                                ),
                            )
                            Spacer(modifier = Modifier.height(30.px))

                            DrawScrollableView(modifier = Modifier.width(1000.px)
                                .fillMaxHeight()) {
                                Column {
                                    Content(viewModel)
                                }
                            }
                        }

                    }

                }
            }
        }
        Log.e(TAG, "onCreate");
    }

    @Composable
    fun ColumnScope.Content(viewmodel: AddQAViewModel) {
        val questions = remember {
            viewmodel.questionList
        }

        val answer = remember { mutableStateOf(viewmodel.answer.answer) }

        questions.forEachIndexed { index, item ->
            Row(verticalAlignment = Alignment.CenterVertically) {
                BasicText(
                    text = "指       令 " + (index + 1),
                    style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                        fontSize = MyFont_Size,
                        color = MYBLACK
                    ),
                    modifier = Modifier.align(Alignment.CenterVertically)
                )
                Spacer(modifier = Modifier.width(20.px))
                CustomStyledTextField20(
                    text = item.question,
                    placeHolder = "请输入",
                    size = DpSize(560.px, 50.px)
                ) {
                    questions[index] = questions[index].copy(question = it)
                    Log.e(TAG, " items[index] " + questions[index]);
                }
                Spacer(modifier = Modifier.width(20.px))
                Image(
                    painter = painterResource(id = if (index == 0) R.drawable.add2 else R.drawable.plus),
                    contentDescription = "",
                    modifier = Modifier.clickable {
                        if (index == 0) questions.add(QuestionBean())
                        // 删除当前的item
                        else if (questions.size > 1)
                            questions.remove(item)
                    })
            }
            Spacer(modifier = Modifier.height(30.px))
        }

        Spacer(modifier = Modifier.height(30.px))
        Row {
            BasicText(
                text = "返回内容",
                style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                    fontSize = MyFont_Size,
                    color = MYBLACK
                ),
                modifier = Modifier.align(Alignment.CenterVertically)
            )
            Spacer(modifier = Modifier.width(20.px))
            CustomStyledTextField(singleLine = false,
                text1 = answer.value,
                placeHolder = "请输入",
                search = false,
                size = DpSize(560.px, 127.px),
                onValueChange = { viewmodel.answer.answer = it })
        }

        Spacer(modifier = Modifier.height(50.px))
        MyButton01(
            text = "确认",
            containerColor = MYBLUE,
            textColor = Color.White,
            modifier = Modifier.offset(x = 116.px)
        ) {
            var empty = true;
            questions.forEach {
                if (it.question.trim().isEmpty().not()) {
                    empty = false;
                }
                Log.e(TAG, "" + it);
            }

            if (empty) {
                Toast.makeText(this@AddQAActivity, "请输入指令", Toast.LENGTH_LONG).show()
                return@MyButton01
            }

            if (viewmodel.answer.answer.trim().isEmpty()) {
                Toast.makeText(this@AddQAActivity, "请输入返回内容", Toast.LENGTH_LONG).show()
                return@MyButton01
            }

            // 创建当前日期
            val currentDate = LocalDate.now()

            // 定义日期格式化器
            val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")

            // 格式化日期
            val formattedDate = currentDate.format(formatter)

            //第一步判断问题是否是添加还是更新.
            //全部新增
            if (viewmodel.cmdId == -1L) {
                //新增问题
                val id = DatabaseContext.getCmdDao()
                    .addCmd(CmdBean().apply { name = "没有名字" })

                viewmodel.questionList.forEach {
                    val q = ChatQuestionBean().apply {
                        cmd_id = "" + id
                        question = it.question
                        date = formattedDate
                    }
                    lifecycleScope.launch(IO) {
                        DatabaseContext.getChatQuestionDao().addQuestion(q)
                    }

                }

                //新增答案
                val q1 = ChatAnswerBean().apply {
                    cmd_Id = id.toString()
                    ttsText = viewmodel.answer.answer
                    date = formattedDate
                }
                DatabaseContext.getChatAnswerDao().addAnswer(q1)
            }
            //判断是更新还是新增
            else {
                viewmodel.questionList.forEach { question2 ->
                  //更新
                    if(question2.id >=0){
                        lifecycleScope.launch(IO) {
                            DatabaseContext.getChatQuestionDao().updateQuestionAndDateById(question2.id,question2.question,formattedDate)
                        }

                  }
                    //新增
                    else{
                        val q = ChatQuestionBean().apply {
                            cmd_id = viewmodel.cmdId.toString()
                            question = question2.question
                            date = formattedDate
                        }
                        lifecycleScope.launch(IO) {
                            DatabaseContext.getChatQuestionDao().addQuestion(q)
                        }
                    }
                }
//                答案是更新
                DatabaseContext.getChatAnswerDao().updateAnswerById(viewmodel.answer.id,viewmodel.answer.answer,formattedDate);
            }

//            // 将 items 中的 MutableState<String> 转换为 List<String>
//            val stringList: List<String> = items.map { it.value }.filter { it.isNotBlank() }
//
//            addQA(questions =stringList, answer = answer.value)

            Toast.makeText(this@AddQAActivity,"操作成功",Toast.LENGTH_LONG).show()
            this@AddQAActivity.finish()
        }
        if(1==1)
        MyButton01(
            text = "播放",
            containerColor = MYBLUE,
            textColor = Color.White,
            modifier = Modifier.offset(x = 116.px
            )){
                playTTS(viewmodel.answer.answer)
            }
    }

    companion object {
        val TAG = "AddQAActivity"
    }
}

data class QuestionBean(
    var id: Int = -1,
    var question: String ="",
    var date: String = "",
)

data class AnswerBean(
    var id: Int = -1,
    var answer: String ="",
    var date: String = "",
    )

